package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
@Transactional
@Service
@Slf4j
public class ApUserRealRealServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealService {
    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;


    @Override
    public ResponseResult getAuthList(AuthDto dto) {
        //1. 数据核查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.  条件查询
        //2.1  设置分页参数
        Page<ApUserRealname> realnamePage = new Page<>(dto.getPage(),dto.getSize());
        //2.2  创建查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            queryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> resultPage = page(realnamePage, queryWrapper);


        return new PageResponseResult(dto.getPage(),dto.getSize(),resultPage.getTotal(),resultPage.getRecords());
    }

    /**
     *          实名认证方法
     * @param dto
     * @param status  2 审核失败   9 审核成功
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1.  参数检查
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.  查询当前认证用户是否存在于  app  用户数据库中
        ApUserRealname userRealname = this.getOne(Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getId, dto.getId()));
        if (userRealname == null) {
            log.error("数据库中没有这个用户:{}",dto.getId());
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.  查看此审核用户的审核状态
        if (!AdminConstants.WAIT_AUTH.equals(userRealname.getStatus())) {
            log.error("此用户实名状态不是待审核状态，用户IDd:{}",dto.getId());
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        //2.  查看此审核用户是否存在于  app用户中
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId, userRealname.getId()));
        if (apUser == null) {
            log.error("此实名用户不存在于app用户中，实名Id：{}",userRealname.getId());
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"实名用户不存在于app用户中");
        }
        //  3. 更新用户实名信息
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        //  3.  不通过的话会有不通过的信息 将这个信息存起来
        if (StringUtils.isBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname);
        // 4.  认证通过的话  进行 创建自媒体  和  作者数据库
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //4.1 创建自媒体账户
            WmUser wmUser = createWmUser(dto,apUser);
            //4.2 创建作者信息
            createApAuthor(wmUser);
        }


        return ResponseResult.okResult();
    }

    /**
     *        创建作者用户
     * @param wmUser
     */

    private void createApAuthor(WmUser wmUser) {
        //  检查远程调用是否成功
        ResponseResult<ApAuthor> apAuthorResult = articleFeign.findUserById(wmUser.getApUserId());
        if (apAuthorResult.getCode().intValue() != 0) {
            throw new CustomException(AppHttpCodeEnum.REMOTE_SERVER_ERROR,apAuthorResult.getErrorMessage());
        }
        //  检查作者是否已经存在
        ApAuthor apAuthor = apAuthorResult.getData();
        if (apAuthor != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST);
        }
        //3. 添加作者信息
        apAuthor = new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE); // 自媒体人类型
        apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
        apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
        ResponseResult result = articleFeign.save(apAuthor);
        if (result.getCode() != 0) {
            throw new CustomException(AppHttpCodeEnum.REMOTE_SERVER_ERROR,apAuthorResult.getErrorMessage());

        }

    }

    /**
     *      创建自媒体账户
     * @param dto
     * @param apUser
     * @return
     */
    private WmUser createWmUser(AuthDto dto, ApUser apUser) {

        //1   检测访问是否成功
        ResponseResult<WmUser> wmUserResult = wemediaFeign.findByName(apUser.getName());
        //    状态码=0  为正常
        if (wmUserResult.getCode().intValue() !=0) {
            //CustomException.(AppHttpCodeEnum.SERVER_ERROR,wmUserResult.getErrorMessage());
            throw new CustomException(AppHttpCodeEnum.REMOTE_SERVER_ERROR,wmUserResult.getErrorMessage());
        }
        //  查询自媒体用户是否存在
        WmUser wmUser = wmUserResult.getData();
        if (wmUser != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"自媒体账户已存在");

        }
        wmUser = new WmUser();
        //   添加自媒体用户信息
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0); // 个人
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());

        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if (saveResult.getCode().intValue() != 0) {
            throw new CustomException(AppHttpCodeEnum.REMOTE_SERVER_ERROR,wmUserResult.getErrorMessage());
        }
        return saveResult.getData();


    }


}
